package com.xiaoKe.zhonghzu.global.okhttp;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;
import com.xiaoKe.zhonghzu.global.base.BaseApplication;
import com.xiaoKe.zhonghzu.global.base.BaseResponseBean;
import com.xiaoKe.zhonghzu.global.tool.AppConstant;
import com.xiaoKe.zhonghzu.global.tool.JsonUtils;
import com.xiaoKe.zhonghzu.global.tool.LoggerTool;
import com.xiaoKe.zhonghzu.global.tool.SPUtils;
import com.xiaoKe.zhonghzu.global.tool.ToastUtils;
import com.xiaoKe.zhonghzu.ui.login.LoginActivityPwsWord;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.LoggingPermission;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @ProjectName : xiaoke-pad-zhongzhu
 * @Author : Shijingna
 * @Time : 2024/7/12 15:23
 * @Description : 接口
 */
public class RetrofitClient {
    public static Retrofit retrofit = null;

    public static Retrofit getClient() {
        Gson gson = new GsonBuilder().setLenient().create();
        String string = SPUtils.getString("systemUrl", "");
        if (TextUtils.isEmpty(string)) {
            string = AppConstant.URL;
        }
        retrofit = new Retrofit.Builder()
                .baseUrl(string)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(okHttp())
                .build();
        return retrofit;
    }

    public static OkHttpClient okHttp() {
        // 配置日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        // 创建 OkHttpClient 实例
        return new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request original = chain.request();
                        // 添加请求头部
                        LoggerTool.d("token=" + SPUtils.getString("token", ""));
                        Request.Builder requestBuilder = original.newBuilder()
                                .header("Authorization", "Bearer " + SPUtils.getString("token", ""));
                        Request request = requestBuilder.build();
                        Response response = chain.proceed(request);
                        // 检查响应状态码

                        if (AppConstant.IS_DEBUG) {
                            String result = response.body() != null ? response.body().string() : null;
                            // 打印请求体
                            RequestBody requestBody = request.body();
                            Logger.e("完整请求(url = %s)", request.url());
                            if (requestBody != null) {
                                Buffer buffer = new Buffer();
                                requestBody.writeTo(buffer);
                                Logger.json(buffer.readUtf8());
                            }
                            Logger.e("响应(%s)", request.header("tag"));
                            Logger.json(result);
                            if (null != result) {
                                BaseResponseBean baseResponseBean = JsonUtils.fromJson(result, BaseResponseBean.class);
                                if (null != baseResponseBean) {
                                    if (baseResponseBean.getCode() == 401) {
                                        // 记录 401 错误日志
                                        Logger.e("Unauthorized! Status code: " + response.code());
                                        // 可以抛出异常或其他错误处理
                                        Intent intent = new Intent(BaseApplication.instance, LoginActivityPwsWord.class);
                                        intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TASK | intent.FLAG_ACTIVITY_NEW_TASK);//退出要弹站
                                        BaseApplication.instance.startActivity(intent);
                                    } else if (baseResponseBean.getCode() == 500) {

                                        // 切换到主线程显示Toast
                                        // 备选方案：用Handler切换主线程
                                        Response finalResponse = response;
                                        new Handler(Looper.getMainLooper()).post(() -> {
                                            ToastUtils.showLong(finalResponse.message());
                                        });
                                    }
                                }

                            }


                            // 需要重新创建响应体才能返回
                            response = response.newBuilder().body(okhttp3.ResponseBody.create(response.body().contentType(), result)).build();
                        }
                        return response;
                    }
                }).build();
    }


}